package yong.hee;

import java.util.*;

import twitter4j.*;
import android.app.*;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class CapsuleMain extends ListActivity {

	static final String TAG = "MyTwitter";
	private Twitter mTwitter;
	private int POST_PER_PAGE = 20;
	private MyAuth mAuth;
	private DbHelper mDbHelper;
	private TwitCursorAdapter mAdapter;
	private Cursor mCursor;
	Handler mHandler = new Handler();
	private static final int _DID_LOADING_FRIENDS_TIMELINE = 0;
	private static final int REQUEST_NEW_TWEET = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//TODO: main 레이아웃에 순위 추가. 업다운 화살표 추가.
		setContentView(R.layout.main);
		
		//TODO: DB 테이블에 순위점수 항목 추가.(순위점수를 기준으로 순위가 매겨짐.) 
		mDbHelper = new DbHelper(this);
		mAuth = new MyAuth(this);
		mAuth.init();
		mTwitter = mAuth.getTwitter();
		if (mTwitter == null) mTwitter = mAuth.authorize();
		else startTimeline();
	} 

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		mAuth.doThisOnNewIntent(intent);
		startTimeline();
	}

	private void startTimeline() {
		final ListView lv = getListView();
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View footerView = inflater.inflate(R.layout.add_more_item, null);
		lv.addFooterView(footerView);
		SQLiteDatabase db = mDbHelper.getReadableDatabase();
		
		mCursor = db.query(DbHelper.TABLE, null, null, null, null, null, DbHelper.C_CREATED_AT + " DESC");
		this.startManagingCursor(mCursor);
		mAdapter = new TwitCursorAdapter(this, mCursor);
		lv.setAdapter(mAdapter);
		showDialog(_DID_LOADING_FRIENDS_TIMELINE);
		new Updater(null).start();

		footerView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Paging paging = new Paging(1, POST_PER_PAGE + 1, 1, getPreviousItemId());
				showDialog(_DID_LOADING_FRIENDS_TIMELINE);
				new Updater(paging).start();
			}
		});
		db.close();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case _DID_LOADING_FRIENDS_TIMELINE: {
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Ʈ�� ����� �ε��ϴ� ���Դϴ�...");
				dialog.setIndeterminate(true);
				dialog.setCancelable(true);
				return dialog;
			}
		}
		return null;
	}

	private long getPreviousItemId() {
		long ret = 0;
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		Cursor c = db.query(DbHelper.TABLE, new String[] { "_id" },"retweet_id is null", null, null, null, "_id");
		c.moveToFirst();
		if (c.isAfterLast() == false) {
			ret = c.getLong(0);
			c.moveToNext();
		}
		c.close();
		db.close();
		return ret;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, Menu.NONE, "�� Ʈ�� �ۼ��ϱ�");
		menu.add(Menu.NONE, Menu.FIRST + 2, Menu.NONE, "���� ��ħ");
		menu.add(Menu.NONE, Menu.FIRST + 3, Menu.NONE, "DB �ʱ�ȭ");
		menu.add(Menu.NONE, Menu.FIRST + 4, Menu.NONE, "����");
		return (super.onCreateOptionsMenu(menu));
	}
	
	/** Called when menu item is selected **/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			Intent it = new Intent(this, NewTwit.class);
			startActivityForResult(it, REQUEST_NEW_TWEET);
			return true;
		case Menu.FIRST + 2:
			showDialog(_DID_LOADING_FRIENDS_TIMELINE);
			new Updater(null).start();
			return true;
		case Menu.FIRST + 3:
			SQLiteDatabase db = mDbHelper.getWritableDatabase();
			db.execSQL("DROP TABLE IF EXISTS timeline;");
			db.execSQL(DbHelper.SQL_CREATE_TABLE);
			db.close();
			finish();
			return true;
		case Menu.FIRST + 4:
			finish();
			return true;
		}
		return false;
	}	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == REQUEST_NEW_TWEET) {
			Log.i("MyTwitter", "success!!!");
			try {
				showDialog(_DID_LOADING_FRIENDS_TIMELINE);
				mTwitter.updateStatus(data.getStringExtra("new_tweet"));
				new Updater(null).start();
			} catch (TwitterException e) {
				Log.e(TAG, "Twitter exception: " + e);
			}
		}
	}
	
	@Override
	public void onListItemClick(ListView parent, View v, int position, long id) {
		super.onListItemClick(parent, v, position, id);
		Intent intent = new Intent(this, TwitViewActivity.class);
		intent.putExtra("id", id);
		startActivity(intent);
	}
	
	/** Updates the database from twitter.com data */
	class Updater extends Thread {
		private static final String TAG = "Updater";
		private Paging paging;
				
		public Updater(Paging p) {
			this.paging = p;
		}

		public void run() {
			Log.d(TAG, "Updater ran.");
			List<Status> timeline = null;
			try {
				if (paging == null) timeline = mTwitter.getHomeTimeline();
				else timeline = mTwitter.getHomeTimeline(paging);
				addStatusToDB(timeline);
				mHandler.post(new Runnable() {
					@Override
					public void run() {
						SQLiteDatabase db = mDbHelper.getReadableDatabase();
						Cursor c = db.query(DbHelper.TABLE, null, null, null, null, null, DbHelper.C_CREATED_AT + " DESC");
						mAdapter.changeCursor(c);
						removeDialog(_DID_LOADING_FRIENDS_TIMELINE);
					}
				});
			} catch (TwitterException e) {
				Log.e(TAG, "Updater.run exception: " + e);
			}
		}
		
		private void addStatusToDB(List<Status> timeline) {
			SQLiteDatabase db = new DbHelper(CapsuleMain.this).getWritableDatabase();
			for (Status status : timeline) {
				ContentValues values = DbHelper.statusToContentValues(status);
				// Insert will throw exceptions for duplicate IDs
				try {
					db.insertOrThrow(DbHelper.TABLE, null, values);
				} catch (SQLException e) {

				}
				Log.d(TAG, "Got status: " + status.toString());
			}
			db.close();
		}
	}
}